package com.easylinkin.linkappapi.bim.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.core.models.Operator;
import com.easylinkin.linkappapi.bim.entity.BimProjectImportRecord;
import com.easylinkin.linkappapi.bim.mapper.BimProjectImportRecordMapper;
import com.easylinkin.linkappapi.bim.service.BimProjectImportRecordService;
import com.easylinkin.linkappapi.bim.service.BimTaskService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

/**
 * bim项目导入记录表(BimProjectImportRecord)表服务实现类
 *
 * @author pwqoc
 * @since 2024-05-24 15:02:30
 */
@Service("bimProjectImportRecordService")
public class BimProjectImportRecordServiceImpl extends ServiceImpl<BimProjectImportRecordMapper, BimProjectImportRecord> implements BimProjectImportRecordService {

    public static final String FILE_TYPE = "mpp";

    @Resource
    private BimTaskService taskService;


    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void importProject(MultipartFile file, Operator operator) {
        Assert.notNull(file, FILE_TYPE + "文件不能为空");
        String filename = file.getOriginalFilename();
        Assert.isTrue(StrUtil.equals(FileNameUtil.extName(filename), FILE_TYPE), () -> "请导入"  + FILE_TYPE + "文件");

        filename = FileNameUtil.getPrefix(filename);
        Date importDate = new Date();
        BimProjectImportRecord projectImportRecord = new BimProjectImportRecord()
                .setId(IdUtil.getSnowflake().nextIdStr())
                .setProjectName(filename)
                .setImportDate(importDate)
                .setTenantId(operator.getTenantId())
                .setCreatorId(operator.getUserId())
                .setCreator(operator.getNickname())
                .setCreateTime(importDate)
                .setModifyId(operator.getUserId())
                .setModifier(operator.getNickname())
                .setModifyTime(importDate);
        Assert.isTrue(this.save(projectImportRecord), () -> "保存导入记录失败");

        taskService.importProject(file, projectImportRecord);
    }
}

